package org.saratogaschools.edd.firefighter.client.activity;

import org.saratogaschools.edd.firefighter.client.ClientFactory;
import org.saratogaschools.edd.firefighter.client.place.AddFirePlace;
import org.saratogaschools.edd.firefighter.client.place.FireListPlace;
import org.saratogaschools.edd.firefighter.client.util.AsyncPlaceChange;
import org.saratogaschools.edd.firefighter.client.util.GeocodingResult;
import org.saratogaschools.edd.firefighter.client.util.LatLng;
import org.saratogaschools.edd.firefighter.client.view.AddFireView;
import org.saratogaschools.edd.firefighter.shared.model.Fire;
import org.saratogaschools.edd.firefighter.shared.model.FireFighter;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.geolocation.client.Geolocation;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class AddFireActivity extends AbstractActivity implements AddFireView.Presenter {
	
	private FireFighter fighter;
	private ClientFactory clientFactory;
	private AddFireView view;
	private Geolocation geo;

	public AddFireActivity(AddFirePlace place, ClientFactory clientFactory) {
		this.fighter = place.getFighter();
		this.clientFactory = clientFactory;
		this.geo = Geolocation.getIfSupported();
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		this.view = new AddFireView();
		view.setPresenter(this);
		panel.setWidget(view);
	}

	@Override
	public native void searchForAddresses(String address) /*-{
		var geocoder = new $wnd.google.maps.Geocoder();
		var cbk = this;
		geocoder.geocode( {'address':address}, function(results, status) {
			if (status = $wnd.google.maps.GeocoderStatus.OK) {
				for (var i = 0; i < results.length; i++) {
					cbk.@org.saratogaschools.edd.firefighter.client.activity.AddFireActivity::addGeocodingResult(Lorg/saratogaschools/edd/firefighter/client/util/GeocodingResult;)
						(results[i]);
				}
			}
			else {
				$wnd.alert("Geocoding failed because " + status);
			}
		});
	}-*/;
	
	private void addGeocodingResult(GeocodingResult result) {
		String addr = result.getFormattedAddress();
		LatLng latLng = result.getLocation();
		double lat = latLng.getLatitude();
		double lng = latLng.getLongitude();
		Fire fire = new Fire();
		fire.setLatitude(lat);
		fire.setLongitude(lng);
		fire.setAddress(addr);
		fire.setManagingDepartmentKey(fighter.getDepartmentKey());
		clientFactory.getService().addNewFire(fire, new AsyncCallback<Void>() {
			public void onFailure(Throwable caught) {}
			public void onSuccess(Void result) {
				GWT.runAsync(new AsyncPlaceChange(clientFactory, new FireListPlace(fighter)));
			}
		});
	}

}
